package com.pkche.core.advanced.safety;

import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 权限配置AllocationListener.java <h6></h6>
 *
 * User: Qiang <br/>
 * Describe： <br/>
 *
 * @date 2015年3月7日 下午12:44:42
 */
public class AuthorityConfig extends AllocationListener {
	// <权限名,路径数组>
	public final static Map<String, String[]> Mapper = new HashMap<String, String[]>();
	// 应用权限的路径集合
	private final static HashSet<String> actionSet = new HashSet<String>();
	// 权限映射
	public static final Map<String, Boolean> cacheMapper = new ConcurrentHashMap<String, Boolean>();

	/**
	 * 获取权限映射的配置
	 * 
	 * @return
	 */
	public static Map<String, Boolean> get() {
		return cacheMapper;
	}

	/**
	 * 配置文件路径
	 * 
	 * @param url
	 */
	public AuthorityConfig(URL url) {
		super(url, null);
		// TODO Auto-generated constructor stub
	}

	// 将配置文件描述解析成map
	private void parse(String temp) {
		String[] array = temp.split(";");
		// 清空先
		Mapper.clear();
		actionSet.clear();
		// 遍历更新映射值
		for (String str : array) {
			str = str.trim();
			if (str.length() < 1) {
				continue;
			}
			String[] ks = str.split("=");
			if (ks.length < 2) {
				continue;
			}
			String key = ks[0];
			String value = ks[1];
			int start = value.indexOf("{");
			int end = value.lastIndexOf("}");
			if ((start == -1) || (end == -1)) {
				continue;
			}
			value = value.substring(start + 1, end);
			String[] urls = value.split(",");
			Mapper.put(key.trim(), urls);
			for (String url : urls) {
				// 遍历填充所有路径
				actionSet.add(url);
			}
		}
		// 清空配置缓存
		cacheMapper.clear();
	}

	/**
	 * 验证路径是否需要应用权限
	 * 
	 * @param uri
	 * @return
	 */
	public final static boolean isAppliedActionURI(String uri) {
		return actionSet.contains(uri);
	}

	@Override
	public void reload(List<String> list) {
		// TODO Auto-generated method stub
		StringBuilder data = new StringBuilder();
		for (String str : list) {
			data.append(str);
		}
		parse(data.toString());
	}

	@Override
	public void load(List<String> list) {
		// TODO Auto-generated method stub
		this.reload(list);
	}

}
